library(tidyverse)

t <- data.table::fread('/media/Bill/c50de4b2-1225-48da-a8a3-c20bc6ac9105/eraST_chs_improvement/chs_improvement/ERB/_eraSumireTeru_ADDED/TERU_口上_ストーリー.ERB', sep = '', header = FALSE, encoding = 'UTF-8') |> as_tibble()

annotate_t <- t |>
  mutate(original_trans = str_extract(t$V1, '(?<=TranslatedMark ).+$'),
         id = 1:43736)

origin_index <- str_which(annotate_t$original_trans, '.+')

farce_index <- origin_index[-1] - 1

farce_index_new <- annotate_t[farce_index, ] |>
  filter(str_detect(V1, 'CALL KPRINT')) |>
  mutate(farce = str_extract(V1, '(?<=,\\s")[^A-Z]+(?="$)')) |>
  pull(id)

origin_vector <- annotate_t[farce_index_new + 1, ] |>
  pull(original_trans)

origin_vector |> head()

annotate_t |>
  filter(id %in% farce_index_new) |>
  mutate(V1 = str_replace(V1, '(?<=,\\s")[^A-Z]+(?="$)', origin_vector)) |>
  bind_rows(filter(annotate_t, !(id %in% farce_index_new))) |>
  arrange(id) |>
  select(V1) |>
  write_csv('story.ERB')

